import json
from models.schema_field import SchemaField
from services import BaseService
from decorators import Transactional
from mauth.login_user_holder import LoginUserHolder
from services.schema_field_service import SchemaFieldService
from tools import generate_id, underline_to_camel, underline_to_hump
from tools.db_tool import DbTool
from validators.schema_validator import SchemaForm
schema_field_service = SchemaFieldService(model=SchemaField)


class SchemaService(BaseService):
    """
    数据模型模块业务处理类
    """

    def detail(self, form):
        """
        模型详情
        """
        model = self.db.session.query(self.model).get(form.id.data)
        if model is None:
            return {}
        return model.to_dict(SchemaService.to_vo)

    def page(self, form):
        # 重写分页查询，追加roleIds字段
        pageNum = form.data.get("pageNum", 1)
        pageSize = form.data.get("pageSize", 10)
        page = DbTool.filter_by_custom(self.model).paginate(pageNum, pageSize, False)
        res = self.model.to_page(page, SchemaService.to_vo)
        return res

    @Transactional()
    def save(self, form):
        """
        添加数据模型
        :param form:
        :return:
        """
        model = self.model(**form.data)
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()
        model.variable = json.dumps(form.ext.data, ensure_ascii=False)
        self.db.session.add(model)

    @Transactional()
    def update(self, form):
        """
        修改数据模型
        :param form:
        :return:
        """
        model = self.model(**form.data)
        model.updateUser = LoginUserHolder.get_user_id()
        model.variable = json.dumps(form.ext.data, ensure_ascii=False)
        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )

    def get_by_table_name(self, tableName):
        data = self.db.session.query(self.model).filter_by(tableName=tableName).first()
        if data is not None:
            form = SchemaForm(data.to_dict())
            return SchemaService.wrapper(self.detail(form))
        return {}

    @staticmethod
    def to_vo(data):
        data["ext"] = json.loads(data["variable"])
        tableName = data["tableName"]
        if "_" not in tableName:
            data["moduleName"] = ""
            return data
        data["moduleName"] = tableName.split("_")[0]
        data["tableCamelName"] = underline_to_camel(tableName.split("_")[1])
        data["className"] = underline_to_hump(tableName.split("_")[1])
        return data

    @staticmethod
    def wrapper(data):
        # 追加模型字段列表
        data['columns'] = schema_field_service.list_by_schema_id(data['id'])
        return data
